"""系统更新模型"""
from app.database import get_db_connection

class SystemUpdate:
    """系统更新类"""
    
    @staticmethod
    def get_latest_version():
        """获取最新的系统版本信息"""
        connection = None
        cursor = None
        try:
            connection = get_db_connection()
            cursor = connection.cursor()
            # 查询最新的激活版本
            cursor.execute(
                "SELECT version, description FROM system_updates WHERE is_active = TRUE ORDER BY update_time DESC LIMIT 1"
            )
            result = cursor.fetchone()
            if result:
                return result
            # 如果没有激活的版本，返回最新的版本
            cursor.execute(
                "SELECT version, description FROM system_updates ORDER BY update_time DESC LIMIT 1"
            )
            result = cursor.fetchone()
            return result if result else {'version': 'v1.0.0', 'description': '系统初始版本'}
        except Exception as e:
            print(f"获取最新版本时出错: {e}")
            # 返回默认版本
            return {'version': 'v1.0.0', 'description': '系统初始版本'}
        finally:
            if cursor:
                cursor.close()
            if connection:
                connection.close()
    
    @staticmethod
    def add_update(version, description):
        """添加系统更新记录"""
        connection = None
        cursor = None
        try:
            connection = get_db_connection()
            cursor = connection.cursor()
            # 将之前的更新设置为非激活状态
            cursor.execute("UPDATE system_updates SET is_active = FALSE WHERE is_active = TRUE")
            # 添加新的更新记录
            cursor.execute(
                "INSERT INTO system_updates (version, description, is_active) VALUES (%s, %s, %s)",
                (version, description, True)
            )
            connection.commit()
            return True
        except Exception as e:
            print(f"添加系统更新时出错: {e}")
            if connection:
                connection.rollback()
            return False
        finally:
            if cursor:
                cursor.close()
            if connection:
                connection.close()
    
    @staticmethod
    def get_all_updates():
        """获取所有系统更新记录"""
        connection = None
        cursor = None
        try:
            connection = get_db_connection()
            cursor = connection.cursor()
            cursor.execute(
                "SELECT id, version, description, update_time, is_active FROM system_updates ORDER BY update_time DESC"
            )
            return cursor.fetchall()
        except Exception as e:
            print(f"获取所有更新记录时出错: {e}")
            return []
        finally:
            if cursor:
                cursor.close()
            if connection:
                connection.close()